/*
 * @Author: gggg 1263457581@qq.com
 * @Date: 2025-06-06 15:39:58
 * @LastEditors: gggg 1263457581@qq.com
 * @LastEditTime: 2025-06-06 15:40:06
 * @FilePath: /algorithm-and-data-struct/pool/LockFreeQueue.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <atomic>
#include <array>

template<typename T, size_t N>
class LockFreeQueue {
private:
    std::array<T, N> buffer_;
    std::atomic<size_t> head_ = {0};
    std::atomic<size_t> tail_ = {0};

    static size_t next(size_t idx) { return (idx + 1) % N; }

public:
    bool push(const T& value) {
        size_t tail = tail_.load(std::memory_order_relaxed);
        size_t next_tail = next(tail);
        if (next_tail == head_.load(std::memory_order_acquire))
            return false;  // 队列已满
        buffer_[tail] = value;
        tail_.store(next_tail, std::memory_order_release);
        return true;
    }

    bool pop(T& value) {
        size_t head = head_.load(std::memory_order_relaxed);
        if (head == tail_.load(std::memory_order_acquire))
            return false;  // 队列为空
        value = buffer_[head];
        head_.store(next(head), std::memory_order_release);
        return true;
    }
};
